﻿using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using SZSLSystem.Common;

namespace SZSLSystem.Web.UI
{
    public class ManagePage : System.Web.UI.Page
    {
        protected internal SZSLSystem.Model.WebSet webset;
        protected internal string CurrentAdminName;
        protected internal string CurrentAdminRName;
        protected internal string OrganizationID;
        protected internal string OrganizationName;
        protected internal string AuthorityID;
        protected internal string DataDictionaryID;

        public ManagePage()
        {
            this.Load += new EventHandler(ManagePage_Load);
            webset = new SZSLSystem.BLL.WebSet().loadConfig(Utils.GetXmlMapPath("Configpath"));
            CurrentAdminName = Utils.GetCookie("AdminName", "SZSLSystem") == "" ? ""
               : DESEncrypt.Decrypt(Utils.GetCookie("AdminName", "SZSLSystem"));
            CurrentAdminRName = Utils.GetCookie("AdminRName", "SZSLSystem") == "" ? ""
                : DESEncrypt.Decrypt(Utils.GetCookie("AdminRName", "SZSLSystem"));
            OrganizationID = ConfigurationManager.AppSettings["CompanyCode"].ToString();
            OrganizationName = ConfigurationManager.AppSettings["CompanyName"].ToString();
            AuthorityID = ConfigurationManager.AppSettings["AuthorityCode"].ToString();
            DataDictionaryID = ConfigurationManager.AppSettings["DataDictionaryCode"].ToString();
        }

        private void ManagePage_Load(object sender, EventArgs e)
        {
            if (!IsAdminLogin())
            {
                Response.Write("<script>parent.location.href='" + webset.WebPath + webset.WebManagePath + "/login.aspx'</script>");
                Response.End();
            }
        }

        /// <summary>
        /// 判断管理员是否已经登录(解决Session超时问题)
        /// </summary>
        public bool IsAdminLogin()
        {
            //
            //判断Session是否为Null
            //
            if (Session["AdminNo"] != null && Session["AdminName"] != null && Session["AdminLevel"] != null && Session["AdminType"] != null)
            {
                return true;
            }
            else
            {
                //
                //获取Cookies
                //
                string adminName = Utils.GetCookie("AdminName", "SZSLSystem"); 
                string adminPwd = Utils.GetCookie("AdminPwd", "SZSLSystem");
                if (!string.IsNullOrEmpty(adminName) && !string.IsNullOrEmpty(adminPwd))
                {
                    //
                    //解密用户名
                    //
                    adminName = DESEncrypt.Decrypt(adminName); 
                    SZSLSystem.BLL.Administrator bll = new SZSLSystem.BLL.Administrator();
                    if (bll.chkAdminLogin(adminName, adminPwd))
                    {
                        SZSLSystem.Model.Administrator model = new SZSLSystem.Model.Administrator();
                        model = bll.GetModel(adminName);
                        Session["AdminNo"] = model.ID;
                        Session["AdminName"] = model.UserName;
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 判断用户权限
        /// </summary>
        protected void chkLoginLevel(string pagestr)
        {
            string msbox = "";
            int utype = int.Parse(Session["AdminType"].ToString());
            string ulevel = Session["AdminLevel"].ToString();
            if (utype > 1)
            {
                pagestr += ",";
                if (ulevel.IndexOf(pagestr) == -1)
                {
                    msbox += "<script type=\"text/javascript\">\n";
                    msbox += "parent.jsmsg(350,230,\"警告提示\",\"<b>没有管理权限</b>您没有权限管理该功能，请勿非法进入。\",\"back\")\n";
                    msbox += "</script>\n";
                    Response.Write(msbox);
                    Response.End();
                }
            }
        }

        /// <summary>
        /// 遮罩提示窗口
        /// </summary>
        /// <param name="w">宽度</param>
        /// <param name="h">高度</param>
        /// <param name="msgtitle">窗口标题</param>
        /// <param name="msgbox">提示文字</param>
        /// <param name="url">返回地址</param>
        /// <param name="msgcss">CSS样式</param>
        protected void JscriptMsg(int w, int h, string msgtitle, string msgbox, string url, string msgcss)
        {
            string msbox = "";
            msbox += "<script type=\"text/javascript\">\n";
            msbox += "parent.jsmsg(" + w + "," + h + ",\"" + msgtitle + "\",\"" + msgbox + "\",\"" + url + "\",\"" + msgcss + "\")\n";
            msbox += "</script>\n";
            ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsMsg", msbox);
        }

        /// <summary>
        /// 添加编辑删除提示
        /// </summary>
        /// <param name="msgtitle">提示文字</param>
        /// <param name="url">返回地址</param>
        /// <param name="msgcss">CSS样式</param>
        protected void JscriptPrint(string msgtitle, string url, string msgcss)
        {
            string msbox = "";
            msbox += "<script type=\"text/javascript\">\n";
            msbox += "parent.jsprint(\"" + msgtitle + "\",\"" + url + "\",\"" + msgcss + "\")\n";
            msbox += "</script>\n";
            ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox);
        }

        /// <summary>
        /// 日志写入方法
        /// </summary>
        /// <param name="str"></param>
        protected void SaveLogs(string str, int typeid)
        {
            if (webset.WebLogStatus == 0)
            {
                return;
            }
            SZSLSystem.BLL.SystemLog bll = new SZSLSystem.BLL.SystemLog();
            SZSLSystem.Model.SystemLog model = new SZSLSystem.Model.SystemLog();
            model.Id = Guid.NewGuid();
            if (Session["AdminName"] != null)
            {
                model.UserID = Guid.Parse(DESEncrypt.Decrypt(Utils.GetCookie("AdminID", "SZSLSystem")));
            }
            model.Title = str;
            model.TypeID = typeid;
            model.AddDate = DateTime.Now;
            bll.Add(model);
        }

        /// <summary>
        /// 日志写入方法
        /// </summary>
        /// <param name="str"></param>
        public void SaveLogs(Guid userID, string str, int typeid)
        {
            if (webset.WebLogStatus == 0)
            {
                return;
            }
            SZSLSystem.BLL.SystemLog bll = new SZSLSystem.BLL.SystemLog();
            SZSLSystem.Model.SystemLog model = new SZSLSystem.Model.SystemLog();
            model.Id = Guid.NewGuid();
            model.UserID = userID;
            model.Title = str;
            model.TypeID = typeid;
            model.AddDate = DateTime.Now;
            bll.Add(model);
        }

        /// <summary>
        /// 删除单个文件
        /// </summary>
        /// <param name="_filepath">文件相对路径</param>
        protected void DeleteFile(string _filepath)
        {
            if (string.IsNullOrEmpty(_filepath))
            {
                return;
            }
            string fullpath = Utils.GetMapPath(_filepath);
            if (File.Exists(fullpath))
            {
                File.Delete(fullpath);
            }
        }

        /// <summary>
        /// 生成缩略图的方法
        /// </summary>
        /// <param name="_filepath">文件相对路径</param>
        /// <returns></returns>
        protected string MakeThumbnail(string _filepath)
        {
            if (!string.IsNullOrEmpty(_filepath) && webset.IsThumbnail == 1)
            {
                string _filename = _filepath.Substring(_filepath.LastIndexOf("/") + 1);
                string _newpath = webset.WebFilePath;
                //检查保存的路径 是否有/开头结尾
                if (_newpath.StartsWith("/") == false)
                {
                    _newpath = "/" + _newpath;
                }
                if (_newpath.EndsWith("/") == false)
                {
                    _newpath = _newpath + "/";
                }
                _newpath = _newpath + "Thumbnail/";

                //检查是否有该路径没有就创建
                if (!Directory.Exists(Utils.GetMapPath(_newpath)))
                {
                    Directory.CreateDirectory(Utils.GetMapPath(_newpath));
                }
                //调用生成类方法
                ImageThumbnailMake.MakeThumbnail(_filepath, _newpath + _filename, webset.ProWidth, webset.ProHight, "Cut");

                return _newpath + _filename;
            }

            return _filepath;
        }

        /// <summary>
        /// 用户名权限绑定列表
        /// </summary>
        /// <param name="chk"></param>
        protected void AuthorityBind(string UserID, CheckBoxList chk)
        {
            Guid RoleID = new SZSLSystem.BLL.UserRole().GetModelbyUserID(Guid.Parse(UserID)).RoleID;
            SZSLSystem.BLL.RoleAuthority bll = new BLL.RoleAuthority();
            DataTable tb = bll.GetList("RoleID='" + RoleID.ToString() + "' order by Sort asc").Tables[0];
            DataColumn RoleName = new DataColumn("AuthorityName", typeof(string));
            tb.Columns.Add(RoleName);
            for (int i = 0; i < tb.Rows.Count; i++)
            {
                tb.Rows[i]["AuthorityName"] = new SZSLSystem.BLL.Authority().GetModel(Guid.Parse(tb.Rows[i]["AuthorityID"].ToString())).AuthorityName;
            }
            chk.DataSource = tb;
            chk.DataTextField = "AuthorityName";
            chk.DataValueField = "AuthorityID";
            chk.DataBind();
        }

        /// <summary>
        /// 权限绑定列表
        /// </summary>
        /// <param name="chk"></param>
        protected void AuthorityBind(CheckBoxList chk)
        {
            SZSLSystem.BLL.Authority bll = new BLL.Authority();
            DataTable tb = bll.GetList("Label=0 order by Sort asc").Tables[0];
            chk.DataSource = tb;
            chk.DataTextField = "AuthorityName";
            chk.DataValueField = "ID";
            chk.DataBind();
        }

        /// <summary>
        /// 角色绑定列表
        /// </summary>
        /// <param name="chk"></param>
        protected void RoleBind(CheckBoxList chk)
        {
            SZSLSystem.BLL.Role bll = new BLL.Role();
            DataTable tb = bll.GetList(0, "", " Sort asc").Tables[0];
            chk.DataSource = tb;
            chk.DataTextField = "RoleName";
            chk.DataValueField = "ID";
            chk.DataBind();
        }

        /// <summary>
        /// 部门机构绑定列表
        /// </summary>
        /// <param name="chk"></param>
        protected void OrganizationBind(CheckBoxList chk)
        {
            SZSLSystem.BLL.Organization bll = new BLL.Organization();
            DataTable tb = bll.GetList(Guid.Parse(OrganizationID));
            DataRow[] dr = tb.Select("ClassLayer=1");
            if (dr.Length > 0)
            {
                tb.Rows.Remove(dr[0]);
            }
            chk.DataSource = tb;
            chk.DataTextField = "OrganizationName";
            chk.DataValueField = "ID";
            chk.DataBind();
        }
    }
}
